package com.erpanderp.wam.adm.model.service;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Query;
import org.hibernate.Session;

import com.erpanderp.wam.adm.model.entity.Resource;
import com.erpanderp.wam.adm.model.entity.Service;
import com.erpanderp.wam.adm.model.entity.ServiceGroup;
import com.erpanderp.wam.util.HibernateUtil;

public class ServiceGroupDAO {
	
	public ServiceGroup createServiceGroup(ServiceGroup serviceGroup){
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.getTransaction().begin();
			session.setFlushMode(FlushMode.COMMIT);
			session.save(serviceGroup);
			session.getTransaction().commit();			
		}catch(Exception e){
			e.printStackTrace();
		}
		return serviceGroup;
		
	}
	
	public boolean updateServiceGroup(ServiceGroup serviceGroup){
		boolean serviceGroupUpdated = false;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			session.setFlushMode(FlushMode.COMMIT);
			session.saveOrUpdate(serviceGroup);
			session.getTransaction().commit();			
			serviceGroupUpdated = true;
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return serviceGroupUpdated;
		
	}
	
	public List<ServiceGroup> getAllServiceGroups()
	{
		List<ServiceGroup> serviceGroups = null;
		
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			
			session.beginTransaction();
			
			String queryString = "from ServiceGroup sg order by sg.servicegroupName";
			
			Query query = session.createQuery(queryString);
			query.setCacheable(false);
			serviceGroups = (List<ServiceGroup>) query.list();	
			
			session.close();
			return serviceGroups;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}
	
	public List<ServiceGroup> getServicegroupsByModuleId(Long moduleId){
		List<ServiceGroup> serviceGroups = null;
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			
			session.beginTransaction();
			
			String queryString = "from ServiceGroup sg where sg.module.moduleId = :moduleId";
			
			Query query = session.createQuery(queryString).setParameter("moduleId", moduleId);
			query.setCacheable(false);
			serviceGroups = (List<ServiceGroup>) query.list();	
			
			session.close();
			return serviceGroups;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}
	
	public ServiceGroup getServiceGroupById(Long serviceGroupId)
	{
		ServiceGroup serviceGroup = null;
		
		try{
			Session session = HibernateUtil.getSessionFactory().getCurrentSession();
			session.beginTransaction();
			serviceGroup = (ServiceGroup) session.load(ServiceGroup.class, serviceGroupId);
			//session.close();
			return serviceGroup;
			
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}		
	}
	

}

